<script setup>
import { ref, computed, watch, onActivated } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import SongItem from '@/components/SongItem.vue'
import { usePlayerStore, useMusicStore } from '@/store'

// 添加组件名称
defineOptions({
  name: 'Search'
})

const route = useRoute()
const router = useRouter()
const keyword = computed(() => route.query.keyword || '') // 获取搜索关键词
const localSearchQuery = ref('') // 本地搜索框的值
const loading = computed(() => musicStore.loading) // 加载状态

// 初始化store
const playerStore = usePlayerStore()
const musicStore = useMusicStore()

// 搜索结果
const songs = computed(() => musicStore.searchResults)
const totalCount = computed(() => musicStore.searchResults.length)

// 执行搜索
const performSearch = async (keyword) => {
  const results = await musicStore.searchMusicList(keyword)
  if (results.length > 0) {
    // 将搜索结果添加到播放列表
    playerStore.setPlaylist(results)
  }
}

// 初始化本地搜索关键词
watch(keyword, (newKeyword) => {
  localSearchQuery.value = newKeyword
}, { immediate: true })

// 监听搜索关键词变化
watch(() => route.query.keyword, (newKeyword) => {
  if (newKeyword) {
    performSearch(newKeyword)
  } else {
    musicStore.searchResults = []
  }
}, { immediate: true })

// 当组件被重新激活时执行搜索
onActivated(() => {
  if (keyword.value) {
    performSearch(keyword.value)
  }
})

// 处理搜索
const handleSearch = () => {
  const query = localSearchQuery.value.trim()
  if (query) {
    router.push({
      path: '/search',
      query: { keyword: query }
    })
  }
}

// 处理播放/暂停
const handlePlay = ({ id, playing }) => {
  if (playing) {
    // 找到要播放的歌曲
    const songToPlay = songs.value.find(song => song.id === id)
    if (songToPlay) {
      // 更新到播放器状态
      playerStore.playSong({
        songId: songToPlay.id,
        songName: songToPlay.title,
        artist: songToPlay.artist,
        coverUrl: songToPlay.coverUrl,
        musicUrl: songToPlay.musicUrl,
        album: songToPlay.album,
        isLiked: songToPlay.isFavorite === 1
      })
    }
  } else {
    // 暂停当前播放的歌曲
    playerStore.togglePlay()
  }
}
</script>

<template>
  <div class="search-result">
    <div class="search-container">
      <!-- 顶部搜索框 -->
      <div class="top-search-box">
        <el-input
          v-model="localSearchQuery"
          placeholder="搜索音乐"
          @keyup.enter="handleSearch"
          clearable
          :loading="loading"
        >
          <template #append>
            <el-button @click="handleSearch" :loading="loading">
              <el-icon><search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
      
      <!-- 搜索结果信息 -->
      <div class="search-info" v-if="!loading">
        搜索"{{ keyword }}"，找到 {{ totalCount }} 首单曲
      </div>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <!-- 歌曲列表 -->
      <div class="song-list" v-else>
        <SongItem 
          v-for="(song, index) in songs" 
          :key="song.id"
          :rank="index + 1"
          :songName="song.title"
          :artist="song.artist"
          :isLiked="song.isFavorite === 1"
          :songId="song.id"
          :album="song.album"
          :duration="song.duration"
          :coverUrl="song.coverUrl"
          :musicUrl="song.musicUrl"
          @play="handlePlay"
        />
        
        <div v-if="songs.length === 0" class="no-results">
          未找到相关歌曲
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.search-result {
  padding: 20px 0;
}

.search-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 顶部搜索框 */
.top-search-box {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.top-search-box :deep(.el-input) {
  width: 500px;
}

.top-search-box :deep(.el-input__wrapper) {
  border-radius: 0;
}

.top-search-box :deep(.el-input-group__append) {
  border-radius: 0;
  background-color: #fff;
}

/* 搜索结果信息 */
.search-info {
  font-size: 13px;
  color: #666;
  margin-bottom: 15px;
}

/* 歌曲列表 */
.song-list {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 10px;
}

.no-results {
  padding: 40px 0;
  text-align: center;
  color: #999;
}

/* 添加加载状态样式 */
.loading-container {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

@media (max-width: 768px) {
  .top-search-box :deep(.el-input) {
    width: 100%;
  }
}
</style> 